/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import Controller.Login;
import java.security.MessageDigest;

/**
 *
 * @author Eduardo
 */
public class Salvar extends HttpServlet {

    public Integer exec(String query) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/delc", "root", "password");
        Statement stmt = conn.createStatement();
        Integer id = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
        ResultSet generatedKeys = stmt.getGeneratedKeys();
        if (generatedKeys.next()) {
            id = generatedKeys.getInt(1);
        }
        return id;
    }

    public String createHash(String plainText) throws NoSuchAlgorithmException {
        MessageDigest mdAlgorithm = MessageDigest.getInstance("SHA1");
        mdAlgorithm.update(plainText.getBytes());
        byte[] digest = mdAlgorithm.digest();
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            plainText = Integer.toHexString(0xFF & digest[i]);
            if (plainText.length() < 2) {
                plainText = "0" + plainText;
            }
            hexString.append(plainText);
        }
        return hexString.toString();
    }

    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {
        Integer r = 0;
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(true);
        if (session.getAttribute("talogado") == null) {
            session.setAttribute("error", "Você precisa estar logado!");
            response.sendRedirect("login.jsp");
        } else {
            if (request.getParameter("action").equals("editprofessor")) {
                try {
                    String id = request.getParameter("id");
                    String nome = request.getParameter("nome");
                    String siape = request.getParameter("siape");
                    String cargahoraria = request.getParameter("cargahoraria");
                    String email = request.getParameter("email");

                    String query = "UPDATE professores SET nome = '" + nome + "', siape = '" + siape + "', cargahoraria = '" + cargahoraria + "', email = '" + email + "' WHERE id = '" + id + "'";

                    r = exec(query);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (request.getParameter("action").equals("addprofessor")) {
                try {
                    String id = request.getParameter("id");
                    String nome = request.getParameter("nome");
                    String siape = request.getParameter("siape");
                    String cargahoraria = request.getParameter("cargahoraria");
                    String email = request.getParameter("email");
                    String password = request.getParameter("password");
                    String senha = null;
                    try {
                        senha = createHash(password);
                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    String query = "INSERT INTO professores (nome, siape, cargahoraria, email, password) VALUES ('" + nome + "', '" + siape + "', '" + cargahoraria + "','" + email + "', '" + senha + "')";

                    r = exec(query);
                    System.out.print(r);
                    String query2 = "INSERT INTO preferencias (professor_id, disc_1, disc_2, disc_3) VALUES (" + r + ", 0,0, 0)";
                    r = exec(query2);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (request.getParameter("action").equals("editdisciplina")) {
                try {
                    String id = request.getParameter("id");
                    String nome = request.getParameter("nome");
                    String cod = request.getParameter("cod");
                    String resumo = request.getParameter("resumo");
                    String cargahoraria = request.getParameter("cargahoraria");
                    String creditos = request.getParameter("creditos");

                    String query = "UPDATE disciplinas SET nome = '" + nome + "', cod = '" + cod + "', resumo = '" + resumo + "', cargahoraria = '" + cargahoraria + "', creditos = '" + creditos + "' WHERE id = '" + id + "'";

                    r = exec(query);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (request.getParameter("action").equals("salvaPref")) {
                try {
                    String id = request.getParameter("id");
                    String disc_1 = request.getParameter("disc_1");
                    String disc_2 = request.getParameter("disc_2");
                    String disc_3 = request.getParameter("disc_3");

                    String query = "UPDATE preferencias SET disc_1 = '" + disc_1 + "', disc_2 = '" + disc_2 + "', disc_3 = '" + disc_3 + "'  WHERE professor_id = '" + id + "'";

                    r = exec(query);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (request.getParameter("action").equals("salvaSolicitacao")) {
                try {
                    String curso = request.getParameter("curso");
                    String disciplina = request.getParameter("disc");

                    String hora1 = request.getParameter("horaSel-1");
                    String hora2 = (request.getParameter("horaSel-2") == null) ? null : request.getParameter("horaSel-2");
                    String hora3 = (request.getParameter("horaSel-3") == null) ? null : request.getParameter("horaSel-3");

                    String dias = request.getParameter("diaBoxes");
                    Integer a = dias.split(",").length;
                    String dia1 = null;
                    String dia2 = null;
                    String dia3 = null;
                    String horaa1 = null;
                    String horaa2 = null;
                    String horaa3 = null;

                    if (a == 1) {
                        dia1 = dias.split(",")[0];
                        dia2 = null;
                        dia3 = null;

                        horaa1 = request.getParameter("horaa");
                        horaa2 = null;
                        horaa3 = null;
                    }
                    if (a == 2) {
                        dia1 = dias.split(",")[0];
                        dia2 = dias.split(",")[1];
                        dia3 = null;

                        horaa1 = request.getParameter("horaa");
                        horaa2 = request.getParameter("horaa");
                        horaa3 = null;
                    }
                    if (a == 3) {
                        dia1 = dias.split(",")[0];
                        dia2 = dias.split(",")[1];
                        dia3 = dias.split(",")[2];

                        horaa1 = request.getParameter("horaa");
                        horaa2 = request.getParameter("horaa");
                        horaa3 = request.getParameter("horaa");
                    }




                    String query = "INSERT INTO oferta(id_curso, id_disciplina, hora1, hora2, hora3, dia1, dia2, dia3, horaaula1, horaaula2, horaaula3) VALUES('" + curso + "','" + disciplina + "', '" + hora1 + "', '" + hora2 + "', '" + hora3 + "', " + dia1 + ", " + dia2 + ", " + dia3 + ", " + horaa1 + ", " + horaa2 + ", " + horaa3 + ")";

                    r = exec(query);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (request.getParameter("action").equals("salvaProfSala")) {
                try {
                    String id = request.getParameter("id");
                    String prof = request.getParameter("professor");
                    String sala = request.getParameter("sala");
                    
                    String query = "UPDATE oferta SET id_professor = '" + prof + "', id_sala = '" + sala + "', condicao = 2 WHERE id = '" + id + "'";

                    r = exec(query);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Salvar.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }
}
